package roborally.model.executables;

import roborally.model.evaluables.Evaluable;

/**
 * A class implementing the interface Executable, representing a selection. 
 * A Selection consists of a (Evaluable) condition with an Executable if- and else-part.
 */
public class Selection extends Executable {
	private final Evaluable condition;
	private final Executable ExeIf;
	private final Executable ExeElse;
	/**
	 * Constructs a Selection Executable with a condition and an if and else Executable.
	 * @post The parameters are assigned to their instance variables.
	 */
	public Selection(Evaluable condition, Executable ExeIf, Executable ExeElse){
		this.condition = condition;
		this.ExeIf = ExeIf;
		this.ExeElse = ExeElse;
	}

	@Override
	public boolean executeNextRobotCommand(RobotCommand lastExecutedRobotCommand){
		if( lastExecutedRobotCommand == null || (!this.contains(lastExecutedRobotCommand)) ){
			if(condition.evaluate())
				return ExeIf.executeNextRobotCommand(null);
			else return ExeElse.executeNextRobotCommand(null);
		}
		else{ //the last executed robotcommand is in one of the branches
			if(ExeIf.contains(lastExecutedRobotCommand))
				return ExeIf.executeNextRobotCommand(lastExecutedRobotCommand);
			else return ExeElse.executeNextRobotCommand(lastExecutedRobotCommand);
		}
	}
	@Override
	public boolean contains(Executable other) {
		return ExeIf.contains(other) || ExeElse.contains(other);
	}
}
